package com.sghd.fight.robot.core;

import com.sghd.common.console.ConsoleBean;
import com.sghd.common.console.ConsoleCommand;
import com.sghd.common.socket.client.Client;
import com.sghd.common.socket.client.ClientFactory;
import com.sghd.fight.robot.action.MatchAction;
import com.sghd.fight.robot.action.ReadyAction;
import com.sghd.fight.robot.action.SkillAction;
import com.sghd.pojo.fight.game.RoomVo;
import com.sghd.pojo.fight.game.RoundData;
import com.sghd.pojo.fight.game.SkillReport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;

/**
 * @author wch
 * @date 2018-07-06 12:08
 * @desc 控制器
 **/
@Component
@ConsoleBean
public class Controller {
    private Logger logger = LoggerFactory.getLogger(Controller.class);
    @Autowired
    private ClientFactory clientFactory;
    private ConcurrentMap<Long, Robot> robots = new ConcurrentHashMap<>();
    /**任务高度*/
    private ScheduledExecutorService executor = Executors.newScheduledThreadPool(100);
    private int current = -10000000;

    @ConsoleCommand(name = "run", description = "开始测试")
    public void run(int count) {
        CountDownLatch countDownLatch = new CountDownLatch(count);
        int end = current - count;
        for (; current > end; current--) {
            final long robotId = current;
            executor.submit(() -> {
                try {
                    Client client = clientFactory.getClient("127.0.0.1", 5012);
                    Robot robot = Robot.valueOf(robotId, "ROBOT[" + robotId + "]", client, this);
                    robots.put(robotId, robot);
                    robot.action();
                } catch (Exception e) {
                    logger.error("机器人[{}]发生故障了!", robotId);
                }finally {
                    countDownLatch.countDown();
                }
            });
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
        }
    }

    @ConsoleCommand(name = "close", description = "停止测试")
    public void stop() {
        for (Robot robot : robots.values()) {
            if (robot.isAlive()) {
                synchronized (robot) {
                    robot.setClose(true);
                }
            }
        }
        for (Robot robot : robots.values()) {
            robot.getClient().close();
        }
    }

    @ConsoleCommand(name = "clean", description = "清理数据")
    public void clean() {
        robots.clear();
    }

    //添加定时任务
    public void addWork(Runnable runnable, int delay) {
        executor.schedule(runnable, delay, TimeUnit.MILLISECONDS);
    }

    public void connSuccess(long robotId) {
        Robot robot = robots.get(robotId);
        if(robot == null){
            return;
        }
        robot.setNext(new MatchAction());
    }

    public void roomInfo(long robotId, RoomVo roomVo) {
        Robot robot = robots.get(robotId);
        if(robot == null){
            return;
        }
        robot.setAlive(true);
        robot.setNext(new ReadyAction());
    }

    public void roundStart(long robotId, RoundData roundData) {
        Robot robot = robots.get(robotId);
        if(robot == null){
            return;
        }
        if (roundData.getPlayerId() == robotId) {
            robot.setNext(new SkillAction());
        }
    }

    public void skillInfo(long robotId, SkillReport skillReport) {
        Robot robot = robots.get(robotId);
        if(robot == null){
            return;
        }
        if (skillReport.getId() == robotId) {
            robot.setNext(new SkillAction());
        }
    }
}
